<template>
  <div class="page-main">
    <!--页头 -->
    <Header></Header>
    <div class="register">
      <!-- 表单 -->
      <el-form ref="registerRef" :model="registerForm" :rules="registerRules" class="register-form" label-width="160px">
        <h3 class="title">
          <span>用户注册</span>
          <div class="go-login">
            我已经注册，现在就
            <a href="javascript:void(0)" class="link-type" @click="goLogin()">登录</a>
            <!-- <router-link class="link-type" :to="'/login'">登录</router-link> -->
          </div>
        </h3>
        <el-form-item label="用户名" prop="userCode">
          <el-col :span="15">
            <el-input v-model="registerForm.userCode" type="text" size="large" minlength="6" maxlength="20"
              placeholder="请输入用户名">
              <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
            </el-input>
          </el-col>
          <el-col :span="9">
            <div class="tip-info">
              <el-icon>
                <InfoFilled />
              </el-icon>
              <span>用户名必须以字母开头，长度为6-20位，可包含字母、数字和下划线</span>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item label="真实姓名" prop="userName">
          <el-col :span="15">
            <el-input v-model="registerForm.userName" type="text" size="large" minlength="2" maxlength="6"
              placeholder="请输入真实姓名"></el-input>
          </el-col>
          <el-col :span="9">
            <div class="tip-info">
              <el-icon>
                <InfoFilled />
              </el-icon>
              <span>姓名长度为2-6位</span>
            </div>
          </el-col>
        </el-form-item>
        <el-row>
          <el-col :span="9">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="registerForm.sex" placeholder="请选择">
                <el-option label="男" :value="0" />
                <el-option label="女" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生日" prop="birthday" label-width="135px">
              <el-date-picker v-model="registerForm.birthday" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                placeholder="请选择" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="密码" prop="password">
          <el-col :span="15">
            <el-input v-model="registerForm.password" type="password" size="large" minlength="8" maxlength="20"
              placeholder="请输入密码">
              <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
            </el-input>
          </el-col>
          <el-col :span="9">
            <div class="tip-info">
              <el-icon>
                <InfoFilled />
              </el-icon>
              <span>密码长度为8-20位，且必须包含数字、英文字母以及特殊字符</span>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-col :span="15">
            <el-input v-model="registerForm.confirmPassword" type="password" size="large" placeholder="请输入确认密码">
              <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="电话" prop="officePhone">
          <el-col :span="15">
            <el-input v-model="registerForm.officePhone" type="tel" size="large" placeholder="请输入电话"></el-input>
          </el-col>
          <el-col :span="9">
            <div class="tip-info">
              <el-icon>
                <InfoFilled />
              </el-icon>
              <span>电话格式为010-12345678</span>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item label="手机" prop="mobilePhone">
          <el-col :span="15">
            <el-input v-model="registerForm.mobilePhone" type="tel" size="large" placeholder="请输入手机"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="电子邮件" prop="email">
          <el-col :span="15">
            <el-input v-model="registerForm.email" type="email" size="large" placeholder="请输入电子邮件"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="传真" prop="fax">
          <el-col :span="15">
            <el-input v-model="registerForm.fax" type="text" size="large" placeholder="请输入传真"></el-input>
          </el-col>
        </el-form-item>
        <!-- <el-form-item label="单位" prop="workSpace">
          <el-col :span="15">
            <el-input v-model="registerForm.workSpace" type="text" size="large" placeholder="请输入工作单位"></el-input>
          </el-col>
        </el-form-item> -->
        <el-form-item label="行政区划" prop="province">
          <el-col :span="5">
            <el-select v-model="registerForm.province" @change="chooseProvince" style="width: 100%;" value-key="id"
              placeholder="请选择">
              <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="registerForm.city" placeholder="请选择" @change="chooseCity" style="width: 100%;"
              value-key="id">
              <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="registerForm.county" placeholder="请选择" @change="chooseCounty" style="width: 100%;"
              value-key="id">
              <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaOnOff">
          <el-col :span="5">
            <el-input size="large" v-model="registerForm.code" placeholder="验证码" style="width: 63%"
              @keyup.enter="handleRegister">
              <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
            </el-input>
            <div class="register-code">
              <img :src="codeUrl" @click="getCode" class="register-code-img" />
            </div>
          </el-col>
        </el-form-item>
        <el-form-item class="btn-grounp">
          <el-button :loading="loading" size="large" type="primary" style="margin-left: -160px;"
            @click.prevent="handleRegister">
            <span v-if="!loading">注 册</span>
            <span v-else>注 册 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 页脚 -->
    <Footer></Footer>
  </div>
</template>

<script setup>
// 引入页头组件
import Header from "@/components/Header";
// 引入底部组件
import Footer from "@/components/Footer";
import { ElMessageBox } from "element-plus";
// 引入接口
import { getCodeImg, register } from "@/api/login";
import { getProvince, getChildArea } from "@/api/system/division";
import useUserStore from "@/store/modules/user";

// 当前实例
const { proxy } = getCurrentInstance();
// 全局路由
const router = useRouter();
// 表单form
const registerRef = ref();

// 注册表单
const registerForm = ref({
  userId: "",
  userCode: "",//用户名
  userName: "",//真实姓名
  sex: "",//性别
  birthday: '',//生日
  password: "",//密码
  confirmPassword: "",//确认密码
  officePhone: "",//电话
  mobilePhone: "",//手机
  email: "",//电子邮件
  fax: "",//传真
  orgId: '',//部门id
  // workSpace: '',//单位
  province: '',//省
  city: '',//市
  county: '',//县
  provinceId: '',//省
  cityId: '',//市
  countyId: '',//县
  code: '',//验证码
});
// 用户名校验
const validatorUserName = (rule, value, callback) => {
  const reg = /^[a-zA-Z]\w{5,19}$/g;
  if (!reg.test(value)) {
    callback(new Error("用户名必须以字母开头，长度为6-20位，可包含字母、数字和下划线"));
  } else {
    callback();
  }
};
// 密码校验
const validatorPassword = (rule, value, callback) => {
  const pwdRegex = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}');
  if (!pwdRegex.test(value)) {
    callback(new Error("用户密码长度为8-20位，且必须包含字母、数字、特殊字符。"));
  } else {
    callback();
  }
};
// 密码匹配
const equalToPassword = (rule, value, callback) => {
  if (registerForm.value.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};
// 手机号校验
const validatorPhone = (rule, value, callback) => {
  const reg = /^1[3456789]\d{9}$/;
  if (value && !reg.test(value)) {
    callback(new Error("手机号码格式错误！"));
  } else {
    callback();
  }
};
// 表单验证规则
const registerRules = {
  userCode: [
    { required: true, trigger: "blur", message: "请输入您的用户名" },
    { min: 6, max: 20, message: "用户名长度为6-20位", trigger: "blur" },
    { validator: validatorUserName, trigger: "blur" }
  ],
  userName: [
    { required: true, trigger: "blur", message: "请输入您的真实姓名" },
    { min: 2, max: 6, message: "姓名长度为2-6位", trigger: "blur" }
  ],
  sex: [
    { required: true, trigger: "change", message: "请选择您的性别" },
  ],
  // birthday: [
  //   { required: true, trigger: "change", message: "请选择您的生日" },
  // ],
  password: [
    { required: true, trigger: "blur", message: "请输入您的密码" },
    { validator: validatorPassword, trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, trigger: "blur", message: "请再次输入您的密码" },
    { required: true, validator: equalToPassword, trigger: "blur" }
  ],
  mobilePhone: [
    { required: true, trigger: "blur", message: "请输入您的手机号" },
    { validator: validatorPhone, trigger: "blur" },
  ],
  email: [
    { required: false, type: 'email', message: "邮箱格式错误" },
  ],
  province: [
    { required: true, trigger: "change", message: "请选择行政区划" },
  ],
  // code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};
// 是否开启加载动画
const loading = ref(false);
// 验证码地址
const codeUrl = ref("");
// 是否启用验证码
const captchaOnOff = ref(false);

const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县
/** 获取省列表 */
function getProvinceData() {
  getProvince().then((response) => {
    provinceData.value = response.data;
  });
}
// 选择省份
function chooseProvince(value) {
  registerForm.value.province = value.name;
  registerForm.value.provinceId = value.id;
  registerForm.value.city = null;
  registerForm.value.cityId = null;
  registerForm.value.county = null;
  registerForm.value.countyId = null;
  cityData.value = [];
  areaData.value = [];
  getChildArea(value.id).then(response => {
    cityData.value = response.data;
  });
}
// 选择城市
function chooseCity(value) {
  registerForm.value.city = value.name;
  registerForm.value.cityId = value.id;
  registerForm.value.county = null;
  registerForm.value.countyId = null;
  areaData.value = [];
  getChildArea(value.id).then((response) => {
    areaData.value = response.data;
  });
}
// 选择区县
function chooseCounty(value) {
  registerForm.value.county = value.name;
  registerForm.value.countyId = value.id;
}

// 注册事件
function handleRegister() {
  registerRef.value.validate(valid => {
    if (valid) {
      loading.value = true;
      register({
        ...registerForm.value
      }).then(res => {
        const { code, data } = res;
        if (code == 200 && data == "注册成功") {
            ElMessageBox.alert("<font color='red'>恭喜你，手机号为" + (registerForm.value.mobilePhone) + "的账号注册成功！</font>", "系统提示", {
              dangerouslyUseHTMLString: true,
              type: "success",
            }).then(() => {
              // 跳转登录页
              goLogin();
            }).catch(() => { });
        } else {
          proxy.$modal.msgError(data || '注册失败，请检查信息重试！');
        }
      }).catch((err) => {
        loading.value = false;
        proxy.$modal.msgError(err || '注册失败，请检查信息重试！');
        if (captchaOnOff) {
          getCode();
        }
      });
    }
  });
}
// 获取验证码
function getCode() {
  getCodeImg().then(res => {
    captchaOnOff.value = res.captchaOnOff === undefined ? true : res.captchaOnOff;
    if (captchaOnOff.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      registerForm.value.uuid = res.uuid;
    }
  });
}
// 跳转登录页
function goLogin() {
  useUserStore().logOut().then((res) => {
    console.log(res);
    if (res.retUrl) {
      location.href = res.retUrl;
    } else {
      // 跳转登录页面，通过后端校验实现跳转
      location.href = import.meta.env.VITE_APP_PORTAL_SERVICE;
    }
  })
}

// 挂载
onMounted(() => {
  if (captchaOnOff.value) {
    // 获取验证码
    getCode();
  }
  // 获取省列表
  getProvinceData();
})
</script>

<style lang='scss' scoped>
.page-main {
  min-height: 100%;
}

.register {
  display: flex;
  justify-content: center;
  height: 100%;
  height: calc(100% - 120px);
  background-color: #eeeeee;
  // background-image: url("../assets/images/login-background.jpg");
  background-size: cover;

  .register-form {
    margin: 20px auto;
    border-radius: 6px;
    background: #ffffff;
    width: 1200px;
    padding: 25px 25px 5px 25px;

    .el-input {
      height: 40px;

      input {
        height: 40px;
      }
    }

    .input-icon {
      height: 39px;
      width: 14px;
      margin-left: 0px;
    }

    // 按钮组
    .btn-grounp {
      :deep(.el-form-item__content) {
        margin-left: 0 !important;
        width: 100%;
        justify-content: center;
      }
    }

    // 提示信息
    .tip-info {
      color: #707070;
      line-height: 16px;
      display: flex;
      align-items: center;

      i {
        font-size: 20px;
        color: orange;
        margin-left: 20px;
        margin-right: 5px;
      }
    }
  }
}

// 标题
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  font-size: 28px;

  .go-login {
    color: #707070;
    font-size: 14px;
    float: right;
  }
}

.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.register-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.register-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
